package org.jflame.context.security.shiro;

import org.jflame.context.security.SecurityService;

import java.util.Arrays;
import java.util.Collection;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

public class ShiroSecurityService implements SecurityService {

    @Override
    public Object getPrincipal() {
        return SecurityUtils.getSubject()
                .getPrincipal();
    }

    @Override
    public boolean hasAuthority(String authority) {
        return SecurityUtils.getSubject()
                .isPermitted(authority);
    }

    @Override
    public boolean hasAnyAuthority(String... authorities) {
        if (authorities == null || authorities.length == 0) {
            return false;
        }
        Subject sub = SecurityUtils.getSubject();
        return Arrays.stream(authorities)
                .anyMatch(r -> sub.isPermitted(r));
    }

    @Override
    public boolean hasRole(String role) {
        return SecurityUtils.getSubject()
                .hasRole(role);
    }

    @Override
    public boolean hasAnyRole(String... roles) {
        if (roles == null || roles.length == 0) {
            return false;
        }
        Subject sub = SecurityUtils.getSubject();
        return Arrays.stream(roles)
                .anyMatch(r -> sub.hasRole(r));
    }

    @Override
    public boolean hasAllRoles(Collection<String> roleSet) {
        return SecurityUtils.getSubject()
                .hasAllRoles(roleSet);
    }

}
